package cn.edu.jlu.community.app;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.view.KeyEvent;
import android.view.View;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVUser;
import com.getbase.floatingactionbutton.FloatingActionButton;

import cn.edu.jlu.community.R;
import cn.edu.jlu.community.app.base.DrawerActivity;
import cn.edu.jlu.community.app.other.AboutActivity;
import cn.edu.jlu.community.app.other.InDevActivity;
import cn.edu.jlu.community.app.other.InDevFragment;
import cn.edu.jlu.community.app.post.forum.ForumFragment;
import cn.edu.jlu.community.app.home.HomeFragment;
import cn.edu.jlu.community.app.post.news.NewsFragment;
import cn.edu.jlu.community.app.post.notify.NotificationFragment;
import cn.edu.jlu.community.app.services.express.ExpressFragment;
import cn.edu.jlu.community.app.services.payment.PaymentFragment;
import cn.edu.jlu.community.app.sign.SignActivity;
import cn.edu.jlu.community.server.AppServer;
import cn.edu.jlu.community.util.Log;
import cn.edu.jlu.community.util.ToastUtil;
import it.neokree.materialnavigationdrawer.MaterialNavigationDrawer;
import it.neokree.materialnavigationdrawer.elements.MaterialAccount;
import it.neokree.materialnavigationdrawer.elements.MaterialSection;
import it.neokree.materialnavigationdrawer.elements.listeners.MaterialSectionListener;

public class MainActivity extends DrawerActivity {

    private FragmentManager mFragmentManager;

    private HomeFragment mHomeFragment;
    private ForumFragment mForumFragment;
    private NotificationFragment mNotificationFragment;
    private NewsFragment mNewsFragment;
    private ExpressFragment mExpressFragment;
    private PaymentFragment mPaymentFragment;
    private InDevFragment mInDevFragment;

    private MaterialAccount mAccount;
    private MaterialSection mSignOutSection;

    private MaterialSection mHomeSection;
    private MaterialSection mForumSection;
    private MaterialSection mNotificationSection;
    private MaterialSection mNewsSection;
    private MaterialSection mServiceSection;

    private FloatingActionButton mUnlock;
    private Context mContext;

    @Override
    public void init(Bundle savedInstanceState) {

        mFragmentManager = getSupportFragmentManager();
        mHomeFragment = HomeFragment.newInstance();
        mForumFragment = ForumFragment.newInstance(AppServer.FORUM_CATEGORY);
        mNotificationFragment = NotificationFragment.newInstance(AppServer.NOTIFICATION_CATEGORY);
        mNewsFragment = NewsFragment.newInstance(AppServer.NEWS_CATEGORY);
        mExpressFragment = new ExpressFragment();
        mPaymentFragment = PaymentFragment.newInstance("http://m.dianping.com/changchun");
        mInDevFragment = new InDevFragment();

        setupDrawer();
    }

//    @Override
//    protected void onCreate(Bundle savedInstanceState) {
//        super.onCreate(savedInstanceState);
//        setContentView(R.layout.deprecated_main_activity);
//
//        DataLoader.getBBS();
//        DataLoader.getNews();
//        DataLoader.getNotification();
//
//        // 订阅频道，当该频道消息到来的时候，打开对应的 Activity
//        PushService.setDefaultPushCallback(this, MainActivity.class);
//        PushService.subscribe(this, "public", MainActivity.class);
//        AVInstallation.getCurrentInstallation().saveInBackground(new SaveCallback() {
//            public void done(AVException e) {
//                if (e == null) {
//                    // 保存成功
//                    String installationId = AVInstallation.getCurrentInstallation().getInstallationId();
//                    // 关联  installationId 到用户表等操作……
//                } else {
//                    // 保存失败，输出错误信息
//                }
//            }
//        });
//
//        handler = new Handler() {
//            public void handleMessage(Message msg) {
//                if (!Thread.currentThread().isInterrupted()) {
//                    switch (msg.what) {
//                        case 0:
//                            pd.show();
//                            break;
//                        case 1:
//                            pd.hide();
//                            break;
//                    }
//                }
//                super.handleMessage(msg);
//            }
//        };
//
//    }

    private void setupDrawer() {
        Log.v("setup drawer");
        this.allowArrowAnimation();
        this.setBackPattern(MaterialNavigationDrawer.BACKPATTERN_BACK_TO_FIRST);

        AVUser user = AVUser.getCurrentUser();
        String name = user.getUsername();
        name = name.isEmpty() ? "无名氏" : name;
        mAccount = new MaterialAccount(getResources(), name, "example@email.com",
                R.drawable.ic_head, R.drawable.account_bg);
        addAccount(mAccount);

        AppServer.loadPortrait(user.getObjectId(), new PortraitCallback());

        final Intent signIntent = new Intent(this, SignActivity.class);
        mSignOutSection = newSection("注销", R.drawable.ic_exit_grey600_24dp,
                new MaterialSectionListener() {
                    @Override
                    public void onClick(MaterialSection materialSection) {
                        AppServer.signOut();
                        finish();
                        startActivity(signIntent);
                    }
                });
        addAccountSection(mSignOutSection);

        mHomeSection = newSection(getString(R.string.title_home),
                R.drawable.ic_community_white_24dp, mHomeFragment);
        addSection(mHomeSection);

        mForumSection = newSection(getString(R.string.title_forum),
                R.drawable.ic_forum_white_24dp, mForumFragment);
        addSection(mForumSection);

        mNotificationSection = newSection(getString(R.string.title_notification),
                R.drawable.ic_notifications_white_24dp, mNotificationFragment);
        addSection(mNotificationSection);

        mNewsSection = newSection(getString(R.string.title_news),
                R.drawable.ic_news_white_24dp, mNewsFragment);
        addSection(mNewsSection);

        mServiceSection = newSection(getString(R.string.title_service),
                R.drawable.ic_dashboard_white_24dp, mExpressFragment);
        addSection(mServiceSection);

//        addSection(newSection(getString(R.string.title_payment), R.drawable.ic_wallet_white_24dp, blankFragment));

//        addBottomSection(newSection("设置", R.drawable.ic_settings_white_24dp, intent));
        addBottomSection(newSection("关于", R.drawable.ic_info_white_24dp,
                new Intent(this, AboutActivity.class)));
    }

    private class PortraitCallback implements AppServer.LoaderCallback {
        @Override
        public void onFinish(Object data) {
            mAccount.setPhoto((Bitmap) data);
            notifyAccountDataChanged();
        }

        @Override
        public void onError(AVException e) {

        }
    }

    public void onClick(View view) {
        setSectionById(view.getId());
    }

    public void setSectionById(int id) {
        switch (id) {
            case R.id.forum_card:
                setSection(mForumSection);
                setFragment(mForumFragment, getString(R.string.title_forum));
                break;
            case R.id.notification_card:
                setSection(mNotificationSection);
                setFragment(mNotificationFragment, getString(R.string.title_notification));
                break;
            case R.id.news_card:
                setSection(mNewsSection);
                setFragment(mNewsFragment, getString(R.string.title_news));
                break;
            case R.id.service_card:
                setSection(mServiceSection);
                setFragment(mExpressFragment, getString(R.string.title_service));
                break;
            case R.id.payment_card:
                setSection(mServiceSection);
                setFragment(mPaymentFragment, getString(R.string.title_payment));
                break;
            case R.id.more_card:
                setSection(mServiceSection);
                setFragment(mInDevFragment, getString(R.string.title_more));
                break;
            default:
                break;
        }
    }

    public Fragment getHomeFragment() {
        return mHomeFragment;
    }

    @Override
    protected void onStart() {
        super.onStart();
        // set the indicator for child fragments
        // N.B. call this method AFTER the init() to leave the time to instantiate the ActionBarDrawerToggle
        this.setHomeAsUpIndicator(R.drawable.ic_arrow_back_white_24dp);
    }

    @Override
    public void onHomeAsUpSelected() {
        // when the back arrow is selected this method is called
    }

    @Override
    public void onBackPressed() {
        if (!mPaymentFragment.onBackPressed()) {
            super.onBackPressed();
        }
    }
}
